//
//  DDPlayGameViewController.m
//  Test
//
//  Created by ChenYuan on 2020/9/10.
//  Copyright © 2020 ChenYuan. All rights reserved.
//

#import "DDPlayGameViewController.h"
#import <WebKit/WebKit.h>
#import "WKWebViewJavascriptBridge.h"

@interface DDPlayGameViewController ()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *gameWebView;
@property (nonatomic, strong) WKWebViewJavascriptBridge *bridge;

@property (nonatomic, copy) NSString *redirectUrl;

@end

@implementation DDPlayGameViewController

#pragma mark - LifeCycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setupUI];

    [self setupData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleLightContent;
    } else {
        return UIStatusBarStyleLightContent;
    }
}

#pragma mark - setupUI

- (void)setupUI
{
    [UIApplication sharedApplication].idleTimerDisabled =YES;

    [WKWebViewJavascriptBridge enableLogging];
    WKWebViewJavascriptBridge *bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.gameWebView];
    [bridge setWebViewDelegate:self];
    self.bridge = bridge;
}

#pragma mark - setupData

- (void)configRedirectUrl:(NSString *)redirectUrl
{
    self.redirectUrl = redirectUrl;
}

- (void)setupData
{
    self.view.backgroundColor = [UIColor blackColor];

    [self.gameWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.redirectUrl]]];

    [self.bridge registerHandler:@"getToken" handler:^(id data, WVJBResponseCallback responseCallback) {
        if (responseCallback) {
            NSString * token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
            responseCallback(token);
        }
    }];

    [self.bridge registerHandler:@"back" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}

#pragma mark - properties

- (WKWebView *)gameWebView
{
    if (!_gameWebView) {
        CGRect rect = CGRectMake(0, 0, self.view.bounds.size.width, CGRectGetHeight(self.view.frame));

        WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
        config.allowsInlineMediaPlayback = YES;
        config.mediaTypesRequiringUserActionForPlayback = false;
        _gameWebView = [[WKWebView alloc] initWithFrame:rect configuration:config];
        _gameWebView.navigationDelegate = self;
        [self.view addSubview:_gameWebView];
    }
    return _gameWebView;
}

@end
